/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jas.http.client;

import jas.http.request.HttpRequest;
import jas.http.response.HttpResponse;
import jas.http.response.HttpResponseFormatter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 *
 * @author Asger
 */
public class HttpClientImpl implements HttpClient {
    
    private String address;
    private int port;
    
    public HttpClientImpl(String address, int port) {
        this.address = address;
        this.port = port;
    }

    public HttpResponse sendRequest(HttpRequest request) throws IOException {
        Socket socket = new Socket(address, port);

        OutputStream out = socket.getOutputStream();
        request.print(out);
        out.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        int read = -1;
        while ((read = reader.read()) != -1) {
            buffer.append((char)read);
        }
        String entireResponse = buffer.toString();

        socket.close();

        HttpResponse response = HttpResponseFormatter.parseResponse(entireResponse);

        return response;
    }
    
}
